import { app, BrowserWindow, ipcMain } from "electron";
import { DatabaseFactory, Field } from "./provider/database";
import path from "node:path";

const createWindow = () => {
  const win = new BrowserWindow({
    width: 1440,
    height: 1024,
    webPreferences: {
      preload: path.join(__dirname, "preload.cjs"),
    },
  });
  win.webContents.openDevTools();
  win.loadURL("http://localhost:5173/");
};

app.whenReady().then(async () => {
  const databaseFactory = new DatabaseFactory();
  ipcMain.handle("database:list", async (event: any, params: any) => {
    return await databaseFactory.getList();
  });
  ipcMain.handle("database:create", async (event: any, params: any) => {
    return await databaseFactory.getDatabase(params.name).create();
  });
  ipcMain.handle("table:getList", async (event: any, params: any) => {
    return await databaseFactory.getDatabase(params.name).getTables();
  });
  ipcMain.handle("table:create", async (event: any, fields: any) => {
    let fieldObjects = fields.map((item: any) => {
      let fieldObject = new Field(item.name);
      fieldObject.setDataType(item.dataType, item.limit);
      fieldObject.setUnsigned(item.isUnsigned);
      fieldObject.setNull(item.isNull);
      fieldObject.setPrimaryKey(item.isPrimary);
      fieldObject.setComment(item.remark);
      return fieldObject.toString();
    });

    return await databaseFactory
      .getDatabase("test")
      .createTable("aaa", fieldObjects);
  });
  ipcMain.handle("table:delete", async (event: any, params: any) => {
    console.log(params);
    return await databaseFactory
      .getDatabase(params.databaseName)
      .getTable(params.tableName)
      .remove();
  });
  createWindow();
});
